package com.sourcestream.whileaway;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import java.util.Date;

public class PhoneStateReceiver extends BroadcastReceiver
{
    public void onReceive(Context context, Intent intent)
    {
        SharedPreferences sp = context.getSharedPreferences("PhoneState", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        int missedCalls = sp.getInt("MissedCalls", 0);

        if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING))
        {
            missedCalls++;
            editor.putInt("MissedCalls", missedCalls);
            editor.putLong("LastMissedCall", new Date().getTime());
            editor.commit();
        }
        else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
        {
            if (missedCalls > 0)
            {
                editor.putInt("MissedCalls", missedCalls - 1);
                editor.remove("LastMissedCall");
            }
            editor.commit();
        }
    }
}
